/*
    This file is part of XCOM Mod Manager.

    XCOM Mod Manager is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    XCOM Mod Manager is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with XCOM Mod Manager.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
 * @author Anthony Surma
 */

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
final public class ModLogFile 
{
    final static String LOGFILEEXTENSION    = ".install.log";
    final static String TEMPHASH = "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00";
        
    void writeLog(File modFile, ModInstaller.UPKData[] upkData) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException
    { 	
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(modFile);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();        
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        Element e;
        //doc.getDocumentElement().normalize();
        //System.out.println(doc);
        
        NodeList dataNodeList = doc.getElementsByTagName("Data");
               
        for (int i = 0; i < dataNodeList.getLength(); ++i)
        {
            //System.out.println(dataNodeList.item(i).getTextContent());
            NodeList children = dataNodeList.item(i).getChildNodes();
            
            for (int j = 0; j < children.getLength(); j++) 
            {             
                Node n = children.item(j);
 		   
                if ("SearchHash".equals(n.getNodeName())) 
                {
                    String hash1 = n.getTextContent().split("#")[1];
                    
                    for (ModInstaller.UPKData d : upkData)                        
                    {
                        String hash2 = ModInstaller.bytesToHexString(d.searchHash);
                        
                        if (hash1.equals(hash2))
                        {
                            e = doc.createElement("IsInstalled");
                            e.appendChild(doc.createTextNode(Boolean.toString(d.isInstalled)));                            
                            dataNodeList.item(i).appendChild(e);
                        }                        
                    }
                }                    
            }
        }      
                                
        FileOutputStream fos = new FileOutputStream(new File(modFile.getPath() + LOGFILEEXTENSION));
        fos.write(fixIndents(transformer, doc));
        fos.close();                  
    }
    
    static byte[] fixIndents(Transformer transformer, Document doc) throws TransformerException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();   
        transformer.transform(new DOMSource(doc), new StreamResult(baos));                                                          
        
        return new String(baos.toByteArray()).replaceAll(
                "<IsInstalled>([^<]*)</IsInstalled>", 
                "    <IsInstalled>$1</IsInstalled>").getBytes();
    }
}
